<template>
  <div class="app-container">
    <!-- 统计概览 -->
    <div class="statistics-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon total">
              <el-icon><Message /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ statistics.total }}</div>
              <div class="stat-label">短信总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon sent">
              <el-icon><Promotion /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ statistics.sent }}</div>
              <div class="stat-label">已发送</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon failed">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ statistics.failed }}</div>
              <div class="stat-label">发送失败</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon today">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ statistics.today }}</div>
              <div class="stat-label">今日发送</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 查询表单 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="80px">
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input
            v-model="queryParams.phoneNumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="短信内容" prop="content">
          <el-input
            v-model="queryParams.content"
            placeholder="请输入短信内容关键字"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="发送状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择发送状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="发送成功" value="success" />
            <el-option label="发送失败" value="failed" />
            <el-option label="发送中" value="sending" />
            <el-option label="待发送" value="pending" />
          </el-select>
        </el-form-item>
        <el-form-item label="短信类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择短信类型" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="通知短信" value="notification" />
            <el-option label="验证码" value="verification" />
            <el-option label="营销短信" value="marketing" />
            <el-option label="告警短信" value="alarm" />
          </el-select>
        </el-form-item>
        <el-form-item label="发送时间">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="never" class="toolbar-card">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleSend">
            <el-icon><Promotion /></el-icon>
            发送短信
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" @click="handleBatchSend" :disabled="!selectedRows.length">
            <el-icon><Message /></el-icon>
            批量重发
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" @click="showStatistics">
            <el-icon><DataAnalysis /></el-icon>
            统计分析
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="smsList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="手机号码" prop="phoneNumber" width="130" align="center" />
        <el-table-column label="短信内容" prop="content" min-width="200" show-overflow-tooltip />
        <el-table-column label="短信类型" prop="type" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="small">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发送状态" prop="status" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发送时间" prop="sendTime" width="160" align="center" />
        <el-table-column label="发送人" prop="sender" width="100" align="center" />
        <el-table-column label="失败原因" prop="failReason" width="150" show-overflow-tooltip />
        <el-table-column label="重试次数" prop="retryCount" width="80" align="center" />
        <el-table-column label="操作" width="260" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button 
              link
              type="success" 
              icon="Refresh"
              @click="handleResend(row)"
              v-if="row.status === 'failed'"
            >
              重发
            </el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 发送短信对话框 -->
    <SmsFormDialog
      v-model:visible="sendDialogVisible"
      :sms-data="currentSms"
      @success="handleSendSuccess"
    />

    <!-- 短信详情对话框 -->
    <SmsDetailDialog
      v-model:visible="detailDialogVisible"
      :sms-data="currentSms"
    />

    <!-- 统计分析对话框 -->
    <SmsStatisticsDialog
      v-model:visible="statisticsDialogVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Message,
  Promotion,
  Warning,
  Calendar,
  Delete,
  Download,
  DataAnalysis
} from '@element-plus/icons-vue'
import SmsFormDialog from './components/SmsFormDialog.vue'
import SmsDetailDialog from './components/SmsDetailDialog.vue'
import SmsStatisticsDialog from './components/SmsStatisticsDialog.vue'

// 响应式数据
const loading = ref(false)
const smsList = ref([])
const selectedRows = ref([])
const total = ref(0)
const dateRange = ref([])

// 对话框显示状态
const sendDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const statisticsDialogVisible = ref(false)

// 当前操作的短信数据
const currentSms = ref({})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  phoneNumber: '',
  content: '',
  status: '',
  type: '',
  startTime: '',
  endTime: ''
})

// 统计数据
const statistics = ref({
  total: 1256,
  sent: 1180,
  failed: 76,
  today: 45
})

// 表单引用
const queryFormRef = ref()

// 获取短信列表
const getList = async () => {
  loading.value = true
  try {
    // 处理时间范围
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = ''
      queryParams.endTime = ''
    }

    // 模拟API调用
    const response = await mockGetSmsList(queryParams)
    smsList.value = response.data
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取短信列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  dateRange.value = []
  queryParams.pageNum = 1
  getList()
}

// 刷新
const handleRefresh = () => {
  getList()
  ElMessage.success('数据已刷新')
}

// 发送短信
const handleSend = () => {
  currentSms.value = {}
  sendDialogVisible.value = true
}

// 批量重发
const handleBatchSend = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要重发的短信记录')
    return
  }

  try {
    await ElMessageBox.confirm('确认重发选中的短信记录？', '确认操作', {
      type: 'warning'
    })

    // 模拟批量重发
    await mockBatchResendSms(selectedRows.value.map(row => row.id))
    ElMessage.success('批量重发成功')
    getList()
  } catch {
    // 用户取消
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的短信记录')
    return
  }

  try {
    await ElMessageBox.confirm('确认删除选中的短信记录？删除后无法恢复！', '确认删除', {
      type: 'warning'
    })

    // 模拟批量删除
    await mockBatchDeleteSms(selectedRows.value.map(row => row.id))
    ElMessage.success('批量删除成功')
    getList()
  } catch {
    // 用户取消
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

// 显示统计分析
const showStatistics = () => {
  statisticsDialogVisible.value = true
}

// 查看详情
const handleView = (row: any) => {
  currentSms.value = { ...row }
  detailDialogVisible.value = true
}

// 重发短信
const handleResend = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认重发短信到 ${row.phoneNumber}？`, '确认重发', {
      type: 'warning'
    })

    // 模拟重发
    await mockResendSms(row.id)
    ElMessage.success('重发成功')
    getList()
  } catch {
    // 用户取消
  }
}

// 删除短信
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认删除短信记录？删除后无法恢复！`, '确认删除', {
      type: 'warning'
    })

    // 模拟删除
    await mockDeleteSms(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch {
    // 用户取消
  }
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 发送成功回调
const handleSendSuccess = () => {
  getList()
  // 更新统计数据
  statistics.value.total++
  statistics.value.today++
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    'notification': 'primary',
    'verification': 'success',
    'marketing': 'warning',
    'alarm': 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const textMap = {
    'notification': '通知短信',
    'verification': '验证码',
    'marketing': '营销短信',
    'alarm': '告警短信'
  }
  return textMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap = {
    'success': 'success',
    'failed': 'danger',
    'sending': 'warning',
    'pending': 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    'success': '发送成功',
    'failed': '发送失败',
    'sending': '发送中',
    'pending': '待发送'
  }
  return textMap[status] || status
}

// 模拟API函数
const mockGetSmsList = (params: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      const mockData = [
        {
          id: 1,
          phoneNumber: '13800138001',
          content: '您的验证码是123456，请在5分钟内使用。',
          type: 'verification',
          status: 'success',
          sendTime: '2024-03-15 14:30:25',
          sender: '张三',
          failReason: '',
          retryCount: 0
        },
        {
          id: 2,
          phoneNumber: '13800138002',
          content: '水库水位已达到警戒线，请立即采取相应措施。',
          type: 'alarm',
          status: 'success',
          sendTime: '2024-03-15 14:25:18',
          sender: '李四',
          failReason: '',
          retryCount: 0
        },
        {
          id: 3,
          phoneNumber: '13800138003',
          content: '系统维护通知：今晚22:00-24:00进行系统维护，期间服务可能中断。',
          type: 'notification',
          status: 'failed',
          sendTime: '2024-03-15 14:20:10',
          sender: '王五',
          failReason: '手机号码不存在',
          retryCount: 2
        },
        {
          id: 4,
          phoneNumber: '13800138004',
          content: '春季防洪调度计划已启动，请相关人员做好准备。',
          type: 'notification',
          status: 'success',
          sendTime: '2024-03-15 14:15:33',
          sender: '赵六',
          failReason: '',
          retryCount: 0
        },
        {
          id: 5,
          phoneNumber: '13800138005',
          content: '您有新的工作任务，请及时查看处理。',
          type: 'notification',
          status: 'sending',
          sendTime: '2024-03-15 14:10:45',
          sender: '钱七',
          failReason: '',
          retryCount: 0
        }
      ]

      resolve({
        data: mockData,
        total: 1256
      })
    }, 500)
  })
}

const mockBatchResendSms = (ids: number[]) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ success: true })
    }, 1000)
  })
}

const mockBatchDeleteSms = (ids: number[]) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ success: true })
    }, 800)
  })
}

const mockResendSms = (id: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ success: true })
    }, 1000)
  })
}

const mockDeleteSms = (id: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ success: true })
    }, 500)
  })
}

// 组件挂载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.statistics-overview {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.sent {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.failed {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.today {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  line-height: 1;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.search-card,
.toolbar-card {
  margin-bottom: 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px;
  margin-bottom: 15px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table .el-table__header-wrapper th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

:deep(.el-tag) {
  border-radius: 4px;
}
</style>